package cn.tedu.web.service.impl;

import java.util.List;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.tedu.web.entity.Category;
import cn.tedu.web.mapper.CategoryMapper;
import cn.tedu.web.mapper.GoodsMapper;
import cn.tedu.web.service.ICategoryService;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author issen
 * @since 2021-09-23
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Resource
	private GoodsMapper goodsMapper;
    // 保存分类
    public Integer save(String name) {
        if (StringUtils.isEmpty(name)) {
            // 传入的名字为空
            return -1;
        }
        Boolean exists = categoryMapper.exists(name);
        if (Boolean.TRUE.equals(exists)) {
            // 传入的名字已存在
            return 0;
        }
        // 保存到数据库
        return categoryMapper.insert(name);
    };

    // 查询所有分类
    public List<Category> findAll() {
        return categoryMapper.findAll();
    };

    /**
     * 删除指定的分类
     */
    public Integer delete(Category category) {
        Integer id = category.getId();
        if (id == null || id < 1) {
            return 0;
        }
        Integer count = goodsMapper.countGoodsByCid(id);
        if (count == null || count < 1) {
            return categoryMapper.delete(id);
        }
        // 通过返回 -1 告知前端，该分类不允许删除，因为存在商品
        return -1;
    }
}
